<template>
	<view class="container">
		<view class="content">
			<view class="form-container">
				<!-- 图片上传区域（移到最顶部） -->
				<view class="image-upload-area">
					<view class="image-list">
						<view v-for="(img, idx) in validImageList" :key="idx" class="image-preview" ref="imgItem" :class="{ dragging: isDragging && dragIndex === idx, dragover: isDragging && dragOverIndex === idx }" @touchstart="onImageTouchStart($event, idx)">
							<image :src="img" mode="aspectFill" class="preview-image" @tap="previewImage(idx)" />
							<view class="delete-btn" @click="deleteImage(idx)">×</view>
						</view>
						<view v-if="validImageList.length < 9" class="upload-box" @click="chooseImage">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传图片</text>
						</view>
					</view>
				</view>
				<!-- 职位名称 -->
				<view class="section-title">职位名称</view>
				<view class="form-item">
					<text class="label required">* 职位名称</text>
					<input type="text" v-model="formData.jobName" placeholder="请输入职位名称" class="input" />
				</view>
				<!-- 职位信息 -->
				<view class="section-title">职位信息</view>
				<view class="form-item">
					<text class="label required">* 职位类别</text>
					<picker @change="onCategoryChange" :value="categoryIndex" :range="categories" class="picker">
						<view class="picker-text">{{categories[categoryIndex]}}</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="label required">* 工作内容</text>
					<textarea v-model="formData.content" placeholder="请输入工作内容，如：岗位要求、人员要求等" class="textarea" maxlength="2000" />
					<view class="desc-tip" style="font-size: 20rpx; color: #999;">请勿填写QQ、微信、电话等联系方式及特殊符号、敏感词等信息，违者将被封号。</view>
				</view>
				<!-- 工作地点 -->
				<view class="section-title">工作地点</view>
				<view class="form-item">
					<text class="label required">* 工作城市</text>
					<input type="text" v-model="formData.city" placeholder="请输入城市" class="input" />
				</view>
				<view class="form-item">
					<text class="label required">* 工作区域</text>
					<input type="text" v-model="formData.district" placeholder="请输入区域" class="input" />
				</view>
				<view class="form-item">
					<text class="label required">* 工作详细地址</text>
					<input type="text" v-model="formData.location" placeholder="请输入详细地址" class="input" />
				</view>
				<view class="desc-tip" style="font-size: 20rpx; color: #999;">请选择真实工作区域，平台将抽查，信息不实将影响职位曝光。</view>

				<!-- 工作周期推荐写法 -->
				<view class="section-title">工作周期</view>
				<view class="form-item">
					<text class="label required">* 工作周期</text>
					<radio-group @change="onPeriodTypeChange">
						<label class="radio-label" v-for="(item, idx) in periodTypeItems" :key="item.value">
							<radio :value="item.value" :checked="idx === periodTypeCurrent" />{{item.name}}
						</label>
					</radio-group>
				</view>
				<view v-if="formData.periodType === 'long'">
					<view class="form-item">
						<text class="label required">* 时长要求</text>
						<picker @change="onDurationChange" :value="durationIndex" :range="durationOptions" class="picker">
							<view class="picker-text">{{ durationOptions[durationIndex] }}</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="label required">* 每周工作周期</text>
						<picker mode="multiSelector" :range="workPeriodOptions" :value="workPeriodIndex" @change="onWorkPeriodChange" @columnchange="onWorkPeriodColumnChange" class="picker">
							<view class="picker-text">
								{{ workPeriodOptions[0][workPeriodIndex[0]] }} → {{ workPeriodOptions[1][workPeriodIndex[1]] }}
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="label">工作时段</text>
						<view v-for="(item, idx) in workTimeList" :key="idx" style="display:flex;align-items:center;margin-bottom:8rpx;">
							<picker mode="time" :value="item.start" @change="onWorkTimeChange(idx, 'start', $event)">
								<view class="picker-text">{{item.start || '上班时间'}}</view>
							</picker>
							<text style="margin:0 12rpx;">→</text>
							<picker mode="time" :value="item.end" @change="onWorkTimeChange(idx, 'end', $event)">
								<view class="picker-text">{{item.end || '下班时间'}}</view>
							</picker>
							<text v-if="workTimeList.length > 1" @click="removeWorkTime(idx)" style="color:#f56c6c;margin-left:12rpx;cursor:pointer;">删除</text>
						</view>
						<button class="add-btn" @click="addWorkTime" type="default" size="mini" style="margin-top:8rpx;">+ 添加工作时段，最多4个</button>
					</view>
				</view>
				<view v-else>
					<view class="form-item">
						<text class="label required">* 工作日期</text>
						<view class="date-picker-group">
							<picker mode="date" :value="shortStartDate" @change="onShortStartDateChange">
								<view class="date-input">{{ shortStartDate || '开始日期' }}</view>
							</picker>
							<text class="date-arrow">→</text>
							<picker mode="date" :value="shortEndDate" @change="onShortEndDateChange">
								<view class="date-input">{{ shortEndDate || '结束日期' }}</view>
							</picker>
						</view>
					</view>
					<view class="form-item">
						<text class="label">工作时段</text>
						<view class="time-picker-group">
							<view v-for="(item, idx) in workTimeList" :key="idx" class="time-range-row">
								<picker mode="time" :value="item.start" @change="onWorkTimeChange(idx, 'start', $event)">
									<view class="time-input">{{item.start || '上班时间'}}</view>
								</picker>
								<text class="date-arrow">→</text>
								<picker mode="time" :value="item.end" @change="onWorkTimeChange(idx, 'end', $event)">
									<view class="time-input">{{item.end || '下班时间'}}</view>
								</picker>
								<text v-if="workTimeList.length > 1" @click="removeWorkTime(idx)" class="remove-time">删除</text>
							</view>
							<button class="add-btn" @click="addWorkTime" type="default" size="mini">+ 添加工作时段，最多4个</button>
						</view>
					</view>
				</view>

				<!-- 薪资待遇 -->
				<view class="section-title">薪资待遇</view>
				<view class="form-item">
					<text class="label required">* 薪资结算</text>
					<radio-group @change="onSalaryTypeChange">
						<label class="radio-label" v-for="(item, idx) in salaryTypeItems" :key="item.value">
							<radio :value="item.value" :checked="idx === salaryTypeCurrent" />{{item.name}}
						</label>
					</radio-group>
				</view>
				<view class="form-item" v-if="formData.salaryType === '其它'">
					<text class="label">自定义结算方式</text>
					<input type="text" v-model="formData.salaryTypeCustom" placeholder="请输入自定义结算方式" class="input" />
				</view>
				<view class="form-item">
					<text class="label required">* 薪资水平</text>
					<view style="display: flex; gap: 16rpx;">
						<input
							type="number"
							v-model="formData.price"
							placeholder="请填写金额"
							class="input"
							style="flex:1;width:0;"
						/>
						<picker
							@change="onSalaryUnitChange"
							:value="salaryUnitIndex"
							:range="salaryUnits"
							class="input"
							style="flex:1;width:0;"
						>
							<view class="picker-text" :style="{ color: salaryUnitIndex === -1 ? '#ccc' : '#333' }">
								{{ salaryUnitIndex === -1 ? '请选择薪资单位' : salaryUnits[salaryUnitIndex] }}
							</view>
						</picker>
					</view>
				</view>
				<view class="form-item">
					<text class="label">薪资说明</text>
					<textarea v-model="formData.salaryDesc" placeholder="如有补充说明请填写" class="textarea" maxlength="500" />
				</view>
				<view class="form-item">
					<text class="label">其他福利</text>
					<uni-data-checkbox
						multiple
						v-model="formData.benefitsList"
						:localdata="benefitsOptions"
						:max="4"
						class="checkbox-group"
					/>
					<view class="desc-tip" :style="{color: (formData.benefitsList && formData.benefitsList.length === 4) ? 'red' : '#999'}">
						最多可选4项
					</view>
				</view>

				<!-- 联系方式 -->
				<view class="section-title">联系方式</view>
				<view class="form-item">
					<text class="label required">* 联系人</text>
					<input type="text" v-model="formData.contactName" placeholder="请输入联系人姓名" class="input" />
				</view>
				<view class="form-item">
					<text class="label required">* 联系电话</text>
					<input type="text" v-model="formData.contactPhone" placeholder="请输入联系电话" class="input" />
				</view>
				<view class="form-item">
					<text class="label">简历接收邮箱</text>
					<input type="text" v-model="formData.contactEmail" placeholder="请输入简历接收邮箱（可选）" class="input" />
				</view>

				<!-- 人员要求 -->
				<view class="section-title">人员要求(选填)</view>
				<view class="form-item">
					<text class="label">学历</text>
					<picker @change="onEducationChange" :value="educationIndex" :range="educationOptions" class="picker">
						<view class="picker-text">{{educationOptions[educationIndex]}}</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="label">性别</text>
					<picker @change="onGenderChange" :value="genderIndex" :range="genderOptions" class="picker">
						<view class="picker-text">{{genderOptions[genderIndex]}}</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="label">年龄</text>
					<input type="text" v-model="formData.age" placeholder="如18-30岁" class="input" />
				</view>

				<!-- 工作环境 -->
				<view class="section-title">工作环境</view>
				<view class="form-item">
					<text class="label">环境描述</text>
					<textarea v-model="formData.envDesc" placeholder="请描述工作环境" class="textarea" maxlength="200" />
				</view>

				<!-- 最大报名人数 -->
				<view class="form-item">
					<text class="label required">* 最大报名人数</text>
					<input type="number" v-model="formData.maxApplyCount" placeholder="请输入最大报名人数" class="input" min="1" />
				</view>
				<!-- 表单底部占位，防止被底部按钮遮挡 -->
				<view style="height: 80px;"></view>
			</view>
		</view>
		<div class="bottom-btns">
			<view class="manage-actions">
				<button class="action-btn delete" @click="onCancel">取消</button>
				<button class="action-btn complete" @click="submitForm">发布</button>
			</view>
		</div>

		<!-- 自定义底部弹窗 -->
		<view v-if="showBottomSheet" class="bottom-sheet-mask" @click="showBottomSheet = false">
			<view class="bottom-sheet" @click.stop>
				<view class="sheet-item" @click="onSheetSelect(0)">从相册选择</view>
				<view class="sheet-item" @click="onSheetSelect(1)">相机<text class="sheet-desc">拍摄与直播</text></view>
				<view class="sheet-item" @click="onSheetSelect(2)">写文字</view>
				<view class="sheet-cancel" @click="showBottomSheet = false">取消</view>
				<view style="height: env(safe-area-inset-bottom, 32rpx);"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config/config.js'
	import { uploadBatch } from '@/api/common'
	import { getTaskInfo, addTask, updateTask } from '@/api/task.js'
	import { getDicts } from '@/api/system/dict.js'
	
	export default {
		data() {
			return {
				formData: {
					content: '',
					price: 1,
					categoryId: 1,
					dueTime: this.formatDate(new Date()),
					status: 0,
					imageList: [],
					city: '上海市',
					district: '浦东新区',
					location: '张江高科',
					workType: '兼职',
					salaryType: '日结',
					contact: '',
					benefits: '',
					contactName: '管理员',
					contactPhone: '18812345678',
					contactEmail: '',
					jobName: '导游',
					education: '',
					gender: '',
					age: '',
					envDesc: '',
					salaryTypeCustom: '',
					benefitsList: [],
					periodType: 'long',
					maxApplyCount: 1
				},
				categories: [],
				categoryOptions: [],
				categoryIndex: 0,
				workTypes: ['全职', '兼职'],
				workTypeIndex: 1,
				salaryTypes: ['日结', '周结', '月结', '完工结算'],
				salaryTypeIndex: 0,
				salaryUnits: ['元/小时', '元/天', '元/次'],
				salaryUnitIndex: -1,
				isTextToImageMode: false,
				isGenerating: false,
				educationOptions: ['不限', '高中', '大专', '本科', '硕士', '博士'],
				genderOptions: ['不限', '男', '女'],
				educationIndex: 0,
				genderIndex: 0,
				workPeriodIndex: [0, 0],
				workPeriodLeft: ['工作日', '周末', '全周'],
				workPeriodRight: [
					Array.from({ length: 5 }, (_, i) => `每周至少工作${i + 1}天`), // 工作日
					Array.from({ length: 2 }, (_, i) => `每周至少工作${i + 1}天`), // 周末
					Array.from({ length: 7 }, (_, i) => `每周至少工作${i + 1}天`), // 全周
				],
				workPeriodOptions: [[], []], // 用于picker绑定
				benefitsOptions: [
					{ text: '高工资', value: '高工资' },
					{ text: '长白班', value: '长白班' },
					{ text: '坐班', value: '坐班' },
					{ text: '四人宿舍', value: '四人宿舍' },
					{ text: '包吃', value: '包吃' },
					{ text: '包住', value: '包住' },
					{ text: '品牌企业', value: '品牌企业' },
					{ text: '近地铁', value: '近地铁' },
					{ text: '就近安排', value: '就近安排' },
					{ text: '报销路费', value: '报销路费' },
					{ text: '灵活排班', value: '灵活排班' },
					{ text: '工作环境好', value: '工作环境好' },
					{ text: '可预支工资', value: '可预支工资' },
					{ text: '有无线网', value: '有无线网' },
					{ text: '补贴提成', value: '补贴提成' },
					{ text: '周末双休', value: '周末双休' },
					{ text: '工作轻松', value: '工作轻松' },
					{ text: '无需经验', value: '无需经验' },
					{ text: '可带手机', value: '可带手机' }
				],
				lastBenefitsList: [],
				showBenefitsLimitTip: false,
				periodTypeItems: [
					{ value: 'long', name: '长期（大于等于2个月）' },
					{ value: 'short', name: '短期（小于2个月）' }
				],
				periodTypeCurrent: 0,
				workTimeList: [{ start: '09:00', end: '18:00' }],
				durationOptions: ['可工作2个月以上', '可工作3个月以上', '可工作4个月以上', '可工作5个月以上', '可工作6个月以上'],
				durationIndex: 0,
				shortStartDate: '',
				shortEndDate: '',
				textInputDialogVisible: false,
				inputText: '',
				touchTimer: null,
				touchStartTime: 0,
				longPressThreshold: 500, // 长按阈值，单位毫秒
				isMouseDown: false,
				dragIndex: null,
				dragOverIndex: null,
				dragY: 0,
				isDragging: false,
				dragStartY: 0,
				isMovable: true,
				imagePos: [
					{ x: 0, y: 0 },
					{ x: 180, y: 0 },
					{ x: 360, y: 0 },
					{ x: 540, y: 0 },
					{ x: 0, y: 180 },
					{ x: 180, y: 180 },
					{ x: 360, y: 180 },
					{ x: 540, y: 180 },
					{ x: 0, y: 360 },
					{ x: 180, y: 360 },
					{ x: 360, y: 360 },
					{ x: 540, y: 360 },
					{ x: 0, y: 540 },
					{ x: 180, y: 540 },
					{ x: 360, y: 540 },
					{ x: 540, y: 540 }
				],
				showBottomSheet: false,
				isEditMode: false,
				taskId: null,
				testType: 'long',
				salaryTypeItems: [
					{ value: '日结', name: '日结' },
					{ value: '周结', name: '周结' },
					{ value: '月结', name: '月结' },
					{ value: '完工结算', name: '完工结算' }
				],
				salaryTypeCurrent: 0
			}
		},
		onLoad(options) {
			console.log('onLoad', options);
			if (!options.taskId) {
				uni.showToast({ title: '参数错误', icon: 'none' });
				setTimeout(() => uni.navigateBack(), 1500);
				return;
			}
			this.isEditMode = true;
			this.taskId = options.taskId;
			const today = new Date().toISOString().slice(0, 10);
			if (!this.shortStartDate) this.shortStartDate = today;
			if (!this.shortEndDate) this.shortEndDate = today;
			this.workPeriodOptions = [
				this.workPeriodLeft,
				this.workPeriodRight[0]
			];
			// 先加载分类，再回显详情
			this.getCategories().then(() => {
				console.log('调用 loadTaskDetail', this.taskId);
				this.loadTaskDetail(this.taskId);
			});
			// 监听TabBar全局发布事件
			uni.$on('show-publish-sheet', this.showActionSheet);
		},
		onReady() {
			this.formData.periodType = 'long';
		},
		onUnload() {
			// 页面卸载时移除监听
			uni.$off('show-publish-sheet', this.showActionSheet);
		},
		methods: {
			getCategories() {
				return getDicts('task_category_type').then(res => {
					if (res.code === 200 && res.data) {
						this.categoryOptions = res.data;
						this.categories = res.data.map(item => item.dictLabel);
						if (this.formData.categoryId) {
							const idx = this.categoryOptions.findIndex(item => item.dictValue == this.formData.categoryId);
							this.categoryIndex = idx > -1 ? idx : 0;
						}
					}
				});
			},
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				if (!token) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}, 1500);
					return false;
				}
				return true;
			},
			onCategoryChange(e) {
				this.categoryIndex = e.detail.value;
				const selectedCategory = this.categoryOptions[this.categoryIndex];
				if (selectedCategory) {
					this.formData.categoryId = selectedCategory.dictValue;
				}
			},
			onDateChange(e) {
				this.formData.dueTime = e.detail.value;
			},
			onWorkTypeChange(e) {
				this.workTypeIndex = e.detail.value;
				this.formData.workType = this.workTypes[this.workTypeIndex];
			},
			onSalaryTypeChange(e) {
				for (let i = 0; i < this.salaryTypeItems.length; i++) {
					if (this.salaryTypeItems[i].value === e.detail.value) {
						this.salaryTypeCurrent = i;
						this.formData.salaryType = this.salaryTypeItems[i].value;
						break;
					}
				}
			},
			onSalaryUnitChange(e) {
				this.salaryUnitIndex = e.detail.value;
				this.formData.salaryUnit = this.salaryUnits[this.salaryUnitIndex];
			},
			// 显示操作菜单
			showActionSheet() {
				this.showBottomSheet = true;
			},
			// 从相册选择图片
			chooseImage() {
				uni.chooseImage({
					count: 9 - this.formData.imageList.length,
					success: (res) => {
						this.formData.imageList = this.formData.imageList.concat(res.tempFilePaths);
						this.initImagePos();
					}
				});
			},
			// 拍摄照片
			takePhoto() {
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success: (res) => {
						this.formData.imageList = [res.tempFilePaths[0]];
					}
				});
			},
			// 删除图片
			deleteImage(idx) {
				this.formData.imageList.splice(idx, 1);
				this.initImagePos();
			},
			async submitForm() {
				// 检查登录状态
				if (!this.checkLoginStatus()) {
					return;
				}
				
				// 表单验证
				if (!this.formData.content) {
					uni.showToast({
						title: '请输入任务详情',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.price) {
					uni.showToast({
						title: '请输入任务预算',
						icon: 'none'
					});
					return;
				}
				if (this.salaryUnitIndex === -1) {
					uni.showToast({
						title: '请选择薪资单位',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.dueTime) {
					uni.showToast({
						title: '请选择截止时间',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.location) {
					uni.showToast({
						title: '请输入工作地点',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.contactName) {
					uni.showToast({
						title: '请输入联系人',
						icon: 'none'
					});
					return;
				}
				if (!this.formData.contactPhone) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					});
					return;
				}
				
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || !userInfo.userId) {
					uni.showToast({
						title: '用户信息获取失败',
						icon: 'none'
					});
					return;
				}
				
				// 设置用户ID
				this.formData.userId = userInfo.userId;
				
				// 处理图片
				let imageList = this.formData.imageList || [];
				let uploadFileNames = [];
				for (let img of imageList) {
					if (img.startsWith('blob:') || img.startsWith('data:')) {
						// 新上传的本地图片，需上传
						const results = await uploadBatch([img]);
						if (results && results.length > 0 && results[0].code === 200 && results[0].fileName) {
							const fileName = results[0].fileName;
							if (/^\/profile\/upload\//.test(fileName) || /^https?:/.test(fileName)) {
								uploadFileNames.push(fileName);
							} else {
								uploadFileNames.push('/profile/upload/' + fileName);
							}
						}
					} else if (/^https?:/.test(img) || img.startsWith('/profile/upload/')) {
						// 已有图片，直接用
						uploadFileNames.push(img);
					} else {
						// 只有文件名，补全路径
						uploadFileNames.push('/profile/upload/' + img);
					}
				}
				this.formData.imageUrls = uploadFileNames.join(',');
				
				// 处理福利
				if (Array.isArray(this.formData.benefitsList)) {
					this.formData.benefits = this.formData.benefitsList.join(',');
				}
				
				// 处理工作周期
				if (Array.isArray(this.workPeriodIndex) && this.workPeriodIndex.length === 2) {
					this.formData.workPeriod = this.workPeriodOptions[0][this.workPeriodIndex[0]] + '-' + this.workPeriodOptions[1][this.workPeriodIndex[1]];
				}
				
				// 处理工作周期类型
				this.formData.periodType = this.formData.periodType;
				
				// 处理工作时段
				if (Array.isArray(this.workTimeList) && this.workTimeList.length > 0) {
					const fixTime = t => t && t.length === 5 ? t : '00:00';
					this.formData.workTime = this.workTimeList
						.map(item => {
							let start = fixTime(item.start);
							let end = fixTime(item.end);
							if (start > end) [start, end] = [end, start];
							return `${start}-${end}`;
						})
						.join(',');
				}
				
				// 同步工作日期
				this.formData.shortStartDate = this.shortStartDate;
				this.formData.shortEndDate = this.shortEndDate;
				
				// 处理薪资单位
				this.formData.salaryUnit = this.salaryUnits[this.salaryUnitIndex];
				
				if (this.isEditMode) {
					// 编辑模式
					const submitData = { ...this.formData, taskId: this.taskId };
					// 只保留后端需要的字段
					delete submitData.imageList;
					delete submitData.benefitsList;
					const res = await updateTask(submitData);
					if (res && res.code === 200) {
						uni.showToast({ title: '修改成功', icon: 'success' });
						// 刷新表单内容
						await this.loadTaskDetail(this.taskId);
						// 不再跳转，留在当前页面
					} else {
						uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
					}
					return;
				} else {
					// 新建模式，调用addTask
					// 2. 发起任务发布请求
					uni.showLoading({ title: '发布中...' });
					try {
						const [err, res] = await uni.request({
							url: `${config.baseUrl}${config.apiPrefix}/system/task`,
							method: 'POST',
							header: {
								'Authorization': `Bearer ${uni.getStorageSync('token')}`,
								'Content-Type': 'application/json'
							},
							data: this.formData
						});
						if (err) throw new Error('请求失败');
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							uni.showToast({ title: '发布成功', icon: 'success' });
							setTimeout(() => {
								uni.redirectTo({ url: '/pages/tabbar/publish/publish-success' });
							}, 800);
							if (this.isEditMode && this.taskId) {
								await this.loadTaskDetail(this.taskId);
							}
							// 新建模式刷新为新建的任务内容
							if (!this.isEditMode && res.data.data && res.data.data.taskId) {
								this.taskId = res.data.data.taskId;
								this.isEditMode = true;
								await this.loadTaskDetail(this.taskId);
							}
							// 不再跳转，留在当前页面
							return;
						} else {
							throw new Error(res.data.msg || '发布失败');
						}
					} catch (error) {
						uni.showToast({ title: error.message || '发布失败，请稍后重试', icon: 'none' });
					} finally {
						uni.hideLoading();
					}
				}
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			onEducationChange(e) {
				this.educationIndex = e.detail.value;
				this.formData.education = this.educationOptions[this.educationIndex];
			},
			onGenderChange(e) {
				this.genderIndex = e.detail.value;
				this.formData.gender = this.genderOptions[this.genderIndex];
			},
			onWorkPeriodChange(e) {
				this.workPeriodIndex = e.detail.value;
				this.formData.workPeriod = this.workPeriodOptions[0][this.workPeriodIndex[0]] + '-' + this.workPeriodOptions[1][this.workPeriodIndex[1]];
			},
			onWorkPeriodColumnChange(e) {
				const { column, value } = e.detail;
				// 如果是第一列（工作日/周末/全周）变化
				if (column === 0) {
					// 更新第二列的选项
					this.$set(this.workPeriodOptions, 1, this.workPeriodRight[value]);
					// 重置第二列的选中索引为0
					this.workPeriodIndex.splice(1, 1, 0);
					// 更新第一列的选中索引
					this.workPeriodIndex.splice(0, 1, value);
				}
			},
			onWorkTimeChange(idx, type, e) {
				this.workTimeList[idx][type] = e.detail.value;
				// 自动校正顺序（点picker确认时立即生效）
				const start = this.workTimeList[idx].start;
				const end = this.workTimeList[idx].end;
				if (start && end && start > end) {
					this.workTimeList[idx].start = end;
					this.workTimeList[idx].end = start;
				}
			},
			addWorkTime() {
				if (this.workTimeList.length >= 4) {
					uni.showToast({ title: '最多添加4个时段', icon: 'none' });
					return;
				}
				this.workTimeList.push({ start: '', end: '' });
			},
			removeWorkTime(idx) {
				this.workTimeList.splice(idx, 1);
			},
			onDurationChange(e) {
				this.durationIndex = e.detail.value;
				this.formData.duration = this.durationOptions[this.durationIndex];
			},
			onShortStartDateChange(e) {
				this.shortStartDate = e.detail.value;
				this.formData.shortStartDate = e.detail.value;
			},
			onShortEndDateChange(e) {
				this.shortEndDate = e.detail.value;
				this.formData.shortEndDate = e.detail.value;
			},
			onPeriodTypeChange(e) {
				for (let i = 0; i < this.periodTypeItems.length; i++) {
					if (this.periodTypeItems[i].value === e.detail.value) {
						this.periodTypeCurrent = i;
						this.formData.periodType = this.periodTypeItems[i].value;
						break;
					}
				}
				if (this.formData.periodType === 'short') {
					const today = new Date().toISOString().slice(0, 10);
					this.shortStartDate = today;
					this.shortEndDate = today;
				}
			},
			previewImage(idx) {
				uni.previewImage({
					urls: this.formData.imageList,
					current: idx
				});
			},
			onImageTouchStart(e, idx) {
				this.dragIndex = idx;
				this.dragStartY = e.touches[0].clientY;
				this.isDragging = true;
				this.dragOverIndex = idx;
			},
			onImageTouchMove(e) {
				if (!this.isDragging || this.dragIndex === null || this.dragIndex === undefined) return;
				const moveY = e.touches[0].clientY;
				uni.createSelectorQuery().in(this).selectAll('.image-preview').boundingClientRect((rects) => {
					let targetIdx = this.dragIndex;
					for (let i = 0; i < rects.length; i++) {
						const centerY = (rects[i].top + rects[i].bottom) / 2;
						if (i !== this.dragIndex && ((moveY > centerY && i > this.dragIndex) || (moveY < centerY && i < this.dragIndex))) {
							targetIdx = i;
							break;
						}
					}
					if (targetIdx !== this.dragIndex) {
						const temp = this.formData.imageList[this.dragIndex];
						this.formData.imageList.splice(this.dragIndex, 1);
						const insertIdx = targetIdx > this.dragIndex ? targetIdx - 1 : targetIdx;
						this.formData.imageList.splice(insertIdx, 0, temp);
						this.dragIndex = insertIdx;
					}
					this.dragOverIndex = targetIdx;
				}).exec();
			},
			onImageTouchEnd() {
				this.isDragging = false;
				this.dragIndex = null;
				this.dragOverIndex = null;
			},
			initImagePos() {
				// 4列布局，每张图片宽高180rpx，间隔20rpx
				const col = 4;
				const size = 180;
				const gap = 20;
				this.imagePos = this.formData.imageList.map((img, idx) => {
					return {
						x: (idx % col) * (size + gap),
						y: Math.floor(idx / col) * (size + gap)
					};
				});
			},
			onSheetSelect(idx) {
				this.showBottomSheet = false;
				switch(idx) {
					case 0: this.chooseImage(); break;
					case 1: this.takePhoto(); break;
					case 2: this.showTextInputDialog(); break;
				}
			},
			async loadTaskDetail(taskId) {
				console.log('进入 loadTaskDetail', taskId);
				const res = await getTaskInfo(taskId);
				console.log('getTaskInfo返回：', res);
				if (res && res.code === 200 && res.data) {
					const data = res.data;
					console.log('后端返回的任务详情：', data);
					let imageList = [];
					if (data.imageUrls) {
						if (Array.isArray(data.imageUrls)) {
							imageList = data.imageUrls;
						} else if (typeof data.imageUrls === 'string') {
							imageList = data.imageUrls.split(',').filter(f => !!f);
						}
						imageList = imageList.map(f => {
							if (/^https?:\/\//.test(f)) return f;
							if (f.startsWith('/')) return config.baseUrl + config.apiPrefix + f;
							return config.baseUrl + config.apiPrefix + '/profile/upload/' + f;
						});
					}
					let workPeriodIndex = [0, 0];
					if (data.workPeriod) {
						const [col1, col2] = String(data.workPeriod).split('-');
						const col1Idx = this.workPeriodOptions[0].indexOf(col1);
						const col2Idx = this.workPeriodOptions[1].indexOf(col2);
						workPeriodIndex = [col1Idx >= 0 ? col1Idx : 0, col2Idx >= 0 ? col2Idx : 0];
					}
					Object.assign(this.formData, data, {
						imageList,
						periodType: (data.periodType === 'short') ? 'short' : 'long'
					});
					console.log('赋值后formData：', this.formData);
					// 分类回显
					if (this.categoryOptions.length > 0) {
						const idx = this.categoryOptions.findIndex(item => item.dictValue == this.formData.categoryId);
						this.categoryIndex = idx > -1 ? idx : 0;
					}
					// 福利回显
					this.$set(
						this.formData,
						'benefitsList',
						data.benefits
							? data.benefits.split(',').map(s => s.trim())
							: []
					);
					// 学历/性别回显
					if (data.education) {
						const idx = this.educationOptions.indexOf(data.education);
						this.educationIndex = idx >= 0 ? idx : 0;
					} else {
						this.educationIndex = 0;
					}
					if (data.gender) {
						const idx = this.genderOptions.indexOf(data.gender);
						this.genderIndex = idx >= 0 ? idx : 0;
					} else {
						this.genderIndex = 0;
					}
					this.onPeriodTypeChange({ detail: { value: this.formData.periodType } });
					this.workPeriodIndex = workPeriodIndex;
					if (this.salaryTypeItems && this.formData.salaryType) {
						const idx = this.salaryTypeItems.findIndex(item => item.value === this.formData.salaryType);
						this.salaryTypeCurrent = idx >= 0 ? idx : 0;
					}
					if (this.periodTypeItems && this.formData.periodType) {
						const idx = this.periodTypeItems.findIndex(item => item.value === this.formData.periodType);
						this.periodTypeCurrent = idx >= 0 ? idx : 0;
					}
					if (data.workTime) {
						this.workTimeList = data.workTime.split(',').map(str => {
							const [start, end] = str.split('-');
							return { start, end };
						});
					} else {
						this.workTimeList = [{ start: '09:00', end: '18:00' }];
					}
					this.shortStartDate = data.shortStartDate || '';
					this.shortEndDate = data.shortEndDate || '';
					// 薪资单位回显
					if (data.salaryUnit) {
						const idx = this.salaryUnits.indexOf(data.salaryUnit);
						this.salaryUnitIndex = idx >= 0 ? idx : -1;
						this.formData.salaryUnit = data.salaryUnit;
					}
					// 调试输出
					console.log('图片回显 imageList:', imageList);
					console.log('最终 formData.imageList:', this.formData.imageList);
				}
			},
			onCancel() {
				uni.navigateBack();
			}
		},
		computed: {
			validImageList() {
				return (this.formData.imageList || []).filter(img => {
					if (!img) return false;
					const s = String(img).trim();
					if (!s) return false;
					// 允许http/https/斜杠/file://、blob:、data:开头或常见图片后缀
					return /^https?:\/\//.test(s) || s.startsWith('/') || s.startsWith('file://') || s.startsWith('blob:') || s.startsWith('data:') || /\.(png|jpg|jpeg|webp|gif)$/i.test(s);
				});
			}
		}
	}
</script>

<style>
	.content {
		padding: 20rpx;
	}
	
	.form-container {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.label {
		width: 140rpx;
		color: #555;
		font-size: 28rpx;
		margin-right: 16rpx;
		text-align: left;
		text-align-last: left;
		padding-left: 0;
		text-indent: 0;
		text-align-vertical: middle;
		text-justify: auto;
	}
	
	.input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.textarea {
		width: 100%;
		height: 200rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
	}
	
	.picker {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
	}
	
	.picker-text {
		line-height: 80rpx;
		font-size: 28rpx;
		color: #333;
		text-align: left;
		padding-left: 16rpx;
	}
	
	.submit-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
		margin-top: 40rpx;
	}
	
	.submit-btn:active {
		opacity: 0.8;
	}
	
	.image-upload-area {
		margin-bottom: 32rpx;
	}
	
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}
	
	.image-preview {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		margin-bottom: 10rpx;
	}
	
	.preview-image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}
	
	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		background: rgba(0,0,0,0.5);
		color: #fff;
		border-radius: 50%;
		width: 36rpx;
		height: 36rpx;
		text-align: center;
		line-height: 36rpx;
		font-size: 28rpx;
	}
	
	.upload-box {
		width: 160rpx;
		height: 160rpx;
		border: 2rpx dashed #ccc;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #999;
		cursor: pointer;
	}
	
	.upload-icon {
		font-size: 48rpx;
	}
	
	.upload-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
		text-align: center;
	}
	
	.text-to-image-area {
		width: 100%;
	}
	
	.generate-btn {
		margin-top: 20rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 28rpx;
		height: 80rpx;
		line-height: 80rpx;
	}
	
	.generate-btn[disabled] {
		background-color: #ccc;
	}
	
	.generate-text-btn {
		margin-top: 20rpx;
		background-color: #f0f0f0;
		padding: 20rpx;
		border-radius: 8rpx;
		text-align: center;
	}
	
	
	.btn-text {
		color: #666;
		font-size: 28rpx;
	}
	
	.publish-btn {
		position: fixed !important;
		bottom: 40px !important;
		left: 50% !important;
		transform: translateX(-50%) !important;
		width: 100% !important;
		max-width: 340px !important;
		display: flex !important;
		flex-direction: row !important;
		flex-wrap: nowrap !important;
		align-items: stretch !important;
		gap: 8px !important;
		z-index: 100 !important;
	}
</style>

<style scoped>
.manage-actions {
	margin-top: 0rpx;
	padding: 0 30rpx;
	display: flex;
	justify-content: space-around;
	.action-btn {
		flex: 1;
		margin: 0 15rpx;
		&.delete {
			background-color: #c8bebe;
			color: white;
		}
		&.complete {
			background-color: #ff6600;
			color: white;
		}
	}
}
.checkbox-label {
  display: inline-flex;
  align-items: center;
  min-width: 120rpx;
  margin: 8rpx 16rpx 8rpx 0;
  font-size: 28rpx;
  vertical-align: middle;
}
.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10rpx;
}
.desc-tip {
  font-size: 24rpx;
  margin-top: 8rpx;
}
.add-btn {
  background: #fafbfc;
  color: #888;
  border: 1rpx dashed #ccc;
  font-size: 24rpx;
  padding: 8rpx 0;
  width: 100%;
  margin-bottom: 8rpx;
}
.date-row, .time-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
}
.date-picker-group, .time-picker-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.date-input, .time-input {
  min-width: 180rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: #fafbfc;
  border: 1rpx solid #e5e6eb;
  border-radius: 6rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
  margin-right: 8rpx;
  margin-bottom: 8rpx;
}
.date-arrow {
  color: #bbb;
  font-size: 32rpx;
  margin: 0 8rpx;
}
.date-icon, .time-icon {
  font-size: 32rpx;
  color: #bbb;
  margin-left: 8rpx;
}
.add-btn-dashed {
  background: #fff;
  color: #888;
  border: 2rpx dashed #ccc;
  font-size: 24rpx;
  padding: 12rpx 0;
  width: 100%;
  margin-top: 8rpx;
  margin-bottom: 8rpx;
  border-radius: 8rpx;
}
.time-range-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}
.remove-time {
  color: #f56c6c;
  margin-left: 12rpx;
  cursor: pointer;
  font-size: 26rpx;
}
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin: 32rpx 0 20rpx 0;
}
.dragging {
  opacity: 0.6;
  border: 2rpx dashed #007aff;
}
.dragover {
  border: 2rpx solid #ff9900;
}
.bottom-sheet-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
}
.bottom-sheet {
  width: 100vw;
  background: #fff;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  padding-bottom: env(safe-area-inset-bottom, 32rpx);
  box-shadow: 0 -4rpx 24rpx rgba(0,0,0,0.08);
  animation: sheetUp 0.2s;
}
@keyframes sheetUp {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}
.sheet-item {
  padding: 32rpx 0;
  text-align: center;
  font-size: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  color: #222;
}
.sheet-desc {
  display: block;
  font-size: 24rpx;
  color: #aaa;
  margin-top: 4rpx;
}
.sheet-cancel {
  padding: 32rpx 0;
  text-align: center;
  font-size: 32rpx;
  color: #007aff;
  margin-top: 12rpx;
  background: #f8f8f8;
  border-radius: 0 0 24rpx 24rpx;
}
.bottom-btns {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 16px;
	background-color: #fff;
	border-top: 1px solid #eee;
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
	z-index: 100;
	gap: 8px;
}
.bottom-btns > div {
	flex: 1;
	min-width: 0;
	border-radius: 8px;
	text-align: center;
	line-height: 44px;
	font-size: 16px;
	cursor: pointer;
}
.bottom-btns > .publish-btn {
	background: #ff9900;
	color: #fff;
}
.bottom-btns > .cancel-btn {
	background: #ff4d4f;
	color: #fff;
}
</style>
